package com.msc.controller.guestmessage;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.msc.common.lang.Result;
import com.msc.common.lang.exception.CiliciliErrorCodeEnum;
import com.msc.controller.guestmessage.vo.GuestMsgVo;
import com.msc.entity.guestmessage.GuestMessage;
import com.msc.service.guestmessage.GuestMessageService;
import com.msc.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author masc
 * @date 2022-07-17 9:59
 * <p>留言板</p>
 */
@RestController
@RequestMapping("/msgBoard")
public class GuestMessageController {
    @Autowired
    private GuestMessageService guestMessageService;

    /**
     * 获取留言墙内容
     */
    @GetMapping("/getAllMessage")
    public Result getMsgByPage(@RequestParam(value = "currentPage", defaultValue = "1") int pageIndex,
                               @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        QueryWrapper<GuestMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(GuestMessage::getStatus, 1);
        queryWrapper.lambda().orderByDesc(GuestMessage::getCreateTime); //根据时间倒序
        Page page = new Page(pageIndex, pageSize);
        IPage<GuestMessage> pageList = guestMessageService.page(page, queryWrapper);

        List<GuestMessage> collect = pageList.getRecords().stream().map(v -> {
            v.setCtTime(DateUtil.dateToString(v.getCreateTime(), DateUtil.DATE_FORMAT_DATETIME2));
            return v;
        }).collect(Collectors.toList());

        pageList.setRecords(collect);
        return Result.succ(pageList);
    }

    /**
     * 创建留言
     */
    @PostMapping("/msgCreate")
    public Result creageMsg(@RequestBody GuestMsgVo guestMsgVo, HttpServletRequest request) {
        boolean succ = guestMessageService.createMsg( request,guestMsgVo);
        if(succ){
            return Result.succ(200,"创建成功了！",succ);
        }
        return Result.succ(CiliciliErrorCodeEnum.IP_NOT_TODAT.getCode(),CiliciliErrorCodeEnum.IP_NOT_TODAT.getMessage(),succ);
    }
}
